#include "NamedPipe.h"
#include <fcntl.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdexcept>
#include <cstring>
#include <iostream>

NamedPipe::NamedPipe(const std::string & pipeName) : pipeName_(pipeName) {
	m_iFd = -1;
   // 检查管道是否已经存在
    if (access(pipeName_.c_str(), F_OK) == -1) {
        // 创建有名管道
        if (mkfifo(pipeName_.c_str(), 0666) == -1) {
            std::cerr << "Error creating named pipe: " << std::strerror(errno) << std::endl;
        }
    }
	
	m_iFd = open(pipeName_.c_str(), O_RDWR);
	if (m_iFd == -1) {
		std::cerr << "Error opening pipe for writing: " << std::strerror(errno) << std::endl;
		return;
	}
}

NamedPipe::~NamedPipe() {
    close(m_iFd);
    // 删除有名管道
    unlink(pipeName_.c_str());
}

// 写入数据到管道
void NamedPipe::write(const std::string& message) {
    if (m_iFd == -1) {
        std::cerr << "Error opening pipe for writing: " << std::strerror(errno) << std::endl;
        return;
    }
    ::write(m_iFd, message.c_str(), message.size() + 1);  // 包括字符串终止符
}

// 从管道读取数据
std::string NamedPipe::read() {
    if (m_iFd == -1) {
        std::cerr << "Error opening pipe for reading: " << std::strerror(errno) << std::endl;
        return "";
    }
    char buffer[256];
    ssize_t bytesRead = ::read(m_iFd, buffer, sizeof(buffer));
    if (bytesRead > 0) {
        return std::string(buffer, bytesRead);
    } else {
        return "";
    }
}


